package com.zs4sdk.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.common.library.data.CommonEventHandler;
import com.common.library.data.CommonHandle;
import com.common.library.data.EventHandler2Get;
import com.common.library.entity.JSONResultEntity;
import com.common.library.util.ActivityHelper;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.common.library.widget.SDKGameClearEditText;
import com.zs4gamesdk.R;
import com.zs4sdk.activity.resetPassword.Zs4GameResetPasswordActivity;
import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
/**
 * Created by Administrator on 2018/7/4.
 */

public class Zs4GameRebindPhoneActivity  extends Zs4GameBaseActivity implements View.OnClickListener {
    private MyCount mSendMessageTimer;
    // 手机验证码输入框
    private EditText etPhoneVerifyCode;
    private EditText etInputRebindPhone;
    // 请求手机验证码的按钮
    private Button btnRequestVerifyCodeView;
    private Button btnConfirm;
    private TextView sdkVerifyPhoneTipTextView;
    // 确认并提交
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_rebind_phone"));
        setTopTitle(ActivityHelper.getStringResId("zs4gameBindSafePhone"));
        init();
    }

    protected void init(){
        super.init();
        btnRequestVerifyCodeView =(Button)this.findViewById(ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_retrieve_textmessage"));
        etPhoneVerifyCode = (EditText)this.findViewById(ActivityHelper.getIdResId("zs4gameviewid_mMessageView_act_retrieve_textmessage"));
        etInputRebindPhone = (EditText)this.findViewById(ActivityHelper.getIdResId("zs4game_input_rebind_phone"));
        btnConfirm = (Button)this.findViewById(ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm"));
        sdkVerifyPhoneTipTextView = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_act_txv_retrieve_pwd_tip"));
        btnConfirm.setOnClickListener(this);
        btnRequestVerifyCodeView.setOnClickListener(this);
    }
    /*定义一个倒计时的内部类*/
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            // 还原btn按钮
            btnRequestVerifyCodeView.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_red_5_bg"));
            btnRequestVerifyCodeView.setClickable(true);
            btnRequestVerifyCodeView.setText(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_send_message_verify")));

        }

        @Override
        public void onTick(long millisUntilFinished) {
            btnRequestVerifyCodeView.setText("重新发送" + millisUntilFinished / 1000 + "秒");
            // 设置btn样式
            btnRequestVerifyCodeView.setBackgroundDrawable(ActivityHelper.getDrawableByName("zs4gamedraw_conner_gray_5_bg"));
            // 设置不可点击
            btnRequestVerifyCodeView.setClickable(false);
        }
    }
    @Override
    public void onClick(View v) {
       super.onClick(v);
       int id = v.getId();
       if(id == ActivityHelper.getIdResId("zs4gameviewid_mMessageBtn_act_retrieve_textmessage")){
           getVerifyCode();
       }else if(id == ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm")){
           reBindPhone();
       }
    }

    private void reBindPhone(){
        String verifyCode = etPhoneVerifyCode.getText().toString();
        if(verifyCode.length() == 0){
            ActivityHelper.showLongToast(this,this.getString(R.string.zs4game_code_no_empty));
            return;
        }
        String phone = etInputRebindPhone.getText().toString();
        if(phone.length() == 0){
            ActivityHelper.showLongToast(this,this.getString(R.string.zs4gamestring_hint_phone_num_not_empty));
            return;
        }
        if (NetworkHelper.isNetworkAvailable(this)) {
            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);
            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phone)));
            paramList.add(new BasicNameValuePair("verifycode", EncryptHelper.encryptByAES(verifyCode)));
            new EventHandler2Get(
                    Extra.URL.REBIND_SAFE_PHONE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new CommonEventHandler.ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {
                    HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                    Log.e("rebind"," rebind result is "+result.toString());
                    Message msg = myHandle.obtainMessage();
                    msg.what = Extra.MessageKey.UPDATE_SAFE_PHONE_STEP_ONE;
                    msg.obj = result;
                    Bundle bundle = new Bundle();
                    msg.setData(bundle);
                    // 发送消息
                    myHandle.sendMessage(msg);
                }
                @Override
                public void doExceptionHandler() {

                }
            });
        }else{
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }



    }
    CommonHandle myHandle = new CommonHandle(Zs4GameRebindPhoneActivity.this, new CommonHandle.HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {
            if (Extra.MessageKey.REQUEST_VERIFY_SUCCESS == msg.what) {
                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);
                if (entity.isSuccess()) {
                } else {
                    sdkVerifyPhoneTipTextView.setText(entity.getDesc());
                }
            }
            if ( Extra.MessageKey.UPDATE_SAFE_PHONE_STEP_ONE == msg.what) {
                //zs4gameBindSafePhoneSuccess
                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);
                boolean is = entity.isSuccess();
            //    is = true;
                if (is) {
                    ActivityHelper.showLongToast(Zs4GameRebindPhoneActivity.this,Zs4GameRebindPhoneActivity.this.getString(R.string.zs4gameBindSafePhoneSuccess));
                    LoginJSONResultEntity entity1 = Zs4GameData.getInstance().getLastLoginedUserInfo();
                    String phone = etInputRebindPhone.getText().toString();
                    entity1.setLoginname(phone);
                    entity1.setNickName(phone);
                    entity1.setMobile(phone);
                    entity1.setUsercode(phone);
                    Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity1);
                    Zs4GameData.getInstance().setLoginJSONResultEntity(entity1);
                    finish();
                    //test
                  //  LoginJSONResultEntity entity2 = Zs4GameData.getInstance().getLastLoginedUserInfo();
                 //   Zs4GameData.getInstance().setLoginJSONResultEntity(entity2);
                //    String loginName = Zs4GameData.getInstance().getLoginName();

                } else {
                    sdkVerifyPhoneTipTextView.setText(entity.getDesc());
                }

             }

        }
    });

    /**
     * 获取验证码
     */
    private void getVerifyCode() {


        String  phoneNumb = etInputRebindPhone.getText().toString();
        // 判断手机号格式：开头是1且为11位
        if (phoneNumb.equals("")) {
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }

        // 判断手机号格式：开头是1且为11位
        if (!Helper.checkMobile(phoneNumb)) {
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }

        if (NetworkHelper.isNetworkAvailable(this)) {
            // 开启计时器
            mSendMessageTimer = new MyCount(Extra.SDKGAMESTRS.GET_AGAIN, 1000);
            mSendMessageTimer.start();

            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumb)));
//            paramList.add(new BasicNameValuePair("sendmode", sendmode));

            new EventHandler2Get(
                    Extra.URL.PHONEVERIFYCODE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new CommonEventHandler.ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {

                    Message msg = myHandle.obtainMessage();

                    msg.what = Extra.MessageKey.REQUEST_VERIFY_SUCCESS;
                    msg.obj = result;

                    Bundle bundle = new Bundle();
//
                    msg.setData(bundle);

                    // 发送消息
                    myHandle.sendMessage(msg);

                }

                @Override
                public void doExceptionHandler() {

                }
            });
        } else {
            sdkVerifyPhoneTipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }
}
